from django.db.models import Q
from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from django.core.cache import cache

from course.models import Book, Category
from course.ser import BookSerializer, CategorySerializer


# Create your views here.


class MyPagination(PageNumberPagination):
    page_size = 1
    page_size_query_param = 'size'
    page_query_param = 'page'
    max_page_size = 10


class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    pagination_class = MyPagination

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get('name')
        query = Q()
        if name:
            query &= Q(name__icontains=name)
        return queryset.filter(query)

    @action(methods=['put'], detail=True)
    def update_status(self, request, pk):
        book = self.get_object()
        book.status = request.data.get('status')
        book.save()
        return Response(status=status.HTTP_200_OK)

    # 图书状态是可借状态的话,后面增加借阅按钮,点击按钮,图书变成已借出的状态,并把借出记录存到redis缓存中
    # @action(methods=['put'], detail=True)
    # def update_status(self, request, pk):
    #     book = self.get_object()
    #     if book.status == 1:
    #         book.status = 2
    #         book.save()
    #         cache.set('book:list', [], 60 * 60 * 24)
    #         return Response(
    #             {
    #                 'code': 200,
    #                 'msg': '借阅成功',
    #                 'data': BookSerializer(book).data
    #             },
    #             status=status.HTTP_200_OK
    #         )
    #     else:
    #         return Response(
    #             {
    #                 'code': 400,
    #                 'msg': '图书已借出',
    #                 'data': BookSerializer(book).data
    #             },
    #             status=status.HTTP_400_BAD_REQUEST
    #         )

    @action(methods=['get'], detail=False)
    def my_borrow_history(self, request):
        key = 'book:list'
        bookList = cache.get(key)
        if bookList:
            return Response({
                'code': 200,
                'msg': '请求成功',
                'data': bookList
            })
        booklist = Book.objects.filter(status=2)
        res = BookSerializer(booklist, many=True)
        if not res.data:
            cache.set(key, [], 60 * 60 * 24)
        cache.set(key, res.data, 60 * 60 * 24)
        return Response({
            'code': 200,
            'msg': '请求成功',
            'data': res.data
        })
